import { authenticateToken } from "../../../lib/auth.js";
import { getConnection } from "../../../lib/db.js";
import { validateLookupType } from "../../../lib/validation.js";

const handler = async function handler(req, res) {
  try {
    const user = req.user;
    const connection = await getConnection();

    if (req.method === "GET") {
      // 获取字典类型列表
      const { page = 1, pageSize = 10, search = "", status = "" } = req.query;
      const offset = (parseInt(page) - 1) * parseInt(pageSize);

      let whereClause = "WHERE tenant_id = ?";
      let queryParams = [user.tenant_id];

      if (search) {
        whereClause +=
          " AND (name LIKE ? OR code LIKE ? OR description LIKE ?)";
        const searchParam = `%${search}%`;
        queryParams.push(searchParam, searchParam, searchParam);
      }

      if (status !== "") {
        whereClause += " AND status = ?";
        queryParams.push(parseInt(status));
      }

      // 获取总数
      const countQuery = `
        SELECT COUNT(*) as total 
        FROM lookup_types 
        ${whereClause}
      `;
      const [countResult] = await connection.execute(countQuery, queryParams);
      const total = countResult[0].total;

      // 获取分页数据
      const dataQuery = `
        SELECT id, code, name, description, is_system, sort_order, status, 
               created_at, updated_at
        FROM lookup_types 
        ${whereClause}
        ORDER BY sort_order ASC, created_at DESC
        LIMIT ? OFFSET ?
      `;
      queryParams.push(parseInt(pageSize), offset);
      const [rows] = await connection.execute(dataQuery, queryParams);

      // 统计每个类型下的字典项数量（按租户聚合，避免动态 IN 绑定问题）
      let itemCounts = {};
      const [itemCountResult] = await connection.execute(
        `
          SELECT type_id, COUNT(*) as item_count
          FROM lookup_items
          WHERE tenant_id = ?
          GROUP BY type_id
        `,
        [user.tenant_id]
      );
      itemCounts = itemCountResult.reduce((acc, row) => {
        acc[row.type_id] = row.item_count;
        return acc;
      }, {});

      // 添加项目数量到结果中
      const data = rows.map((row) => ({
        ...row,
        item_count: itemCounts[row.id] || 0,
      }));

      res.status(200).json({
        success: true,
        data: {
          items: data,
          pagination: {
            page: parseInt(page),
            pageSize: parseInt(pageSize),
            total,
            totalPages: Math.ceil(total / parseInt(pageSize)),
          },
        },
      });
    } else if (req.method === "POST") {
      // 创建字典类型
      if (user.role !== "administrator") {
        return res.status(403).json({
          success: false,
          message: "权限不足，只有管理员才能创建字典类型",
        });
      }

      const validation = validateLookupType(req.body);
      if (!validation.success) {
        return res.status(400).json({
          success: false,
          message: validation.message,
          errors: validation.errors,
        });
      }

      const { code, name, description, sort_order = 0 } = req.body;

      // 检查代码是否已存在
      const [existingType] = await connection.execute(
        "SELECT id FROM lookup_types WHERE tenant_id = ? AND code = ?",
        [user.tenant_id, code]
      );

      if (existingType.length > 0) {
        return res.status(400).json({
          success: false,
          message: "字典类型代码已存在",
        });
      }

      const insertQuery = `
        INSERT INTO lookup_types (tenant_id, code, name, description, sort_order, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, NOW(), NOW())
      `;

      const [result] = await connection.execute(insertQuery, [
        user.tenant_id,
        code,
        name,
        description,
        sort_order,
      ]);

      res.status(201).json({
        success: true,
        message: "字典类型创建成功",
        data: {
          id: result.insertId,
          code,
          name,
          description,
          sort_order,
        },
      });
    } else {
      res.status(405).json({
        success: false,
        message: "不支持的请求方法",
      });
    }
  } catch (error) {
    console.error("Lookup types API error:", error);
    res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

export default authenticateToken(handler);
